package org.client.iot;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.text.TextUtils;


import com.clj.fastble.BleManager;
import com.lucky.base.network.NetworkApi;
import com.lucky.utils.log.LogUtils;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mmkv.MMKV;

import org.client.iot.constant.GlobeConstant;
import org.client.iot.dao.DaoMaster;
import org.client.iot.dao.DaoSession;
import org.client.iot.http.NetworkRequiredInfo;
import org.client.iot.util.MMKVUtils;
//import org.litepal.LitePal;
import org.tzw.template.logger.CrashHandler;
import org.tzw.template.logger.LocalLogger;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * 作者：Administrator on 2022/1/1 00:00
 */
public class LauncherApplication extends Application {
    @SuppressLint("StaticFieldLeak")
    private static Context context;
    private static DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this.getApplicationContext();
        //基于 mmap 内存映射的移动端通用 key-value 组件，底层序列化/反序列化使用 protobuf 实现，性能高，稳定性强
        MMKV.initialize(this);
        //初始化key-value 组件工具类
        MMKVUtils.getInstance();
        LogUtils.init(this, LogUtils.Level.DEBUG, 1024 * 1024 * 20, 30);
//        LitePal.initialize(this);
        LocalLogger.init(this);
        initNetWork(this);
        initBugly(this);
        initBle();
        initDB();
    }

    public static Context getContext() {
        return context;
    }

    private void initBle() {
        BleManager.getInstance().init(this);
        BleManager.getInstance().enableLog(true).setReConnectCount(1, 5000).setOperateTimeout(10 * 1000);
    }

    private void initDB() {
        daoSession = new DaoMaster(new DaoMaster.DevOpenHelper(getApplicationContext(), "iot.db", null).getWritableDb()).newSession();
    }

    public static DaoSession getDaoSession() {
        return daoSession;
    }

    private void initBugly(Context context) {
        CrashHandler.getInstance().init(context);
        String packageName = context.getPackageName();
        String processName = getProcessName(android.os.Process.myPid());
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
//        CrashReport.setServerUrl("https://android.crashsight.qq.com/pb/async");
        CrashReport.initCrashReport(context, "84d4877af7", true, strategy);

    }

    // 获取进程pid对应的进程名
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    // 初始化网络
    public static void initNetWork(Application application) {
        String ip = (String) MMKVUtils.getInstance().get("ip", "");
        String port = (String) MMKVUtils.getInstance().get("port", "");
        if (!ip.isEmpty() && !port.isEmpty()) {
            NetworkApi.init(new NetworkRequiredInfo(application),
                    GlobeConstant.HttpConfig.HOST_URL + ":" + GlobeConstant.HttpConfig.POST,
                    ip + ":" + port);
        } else {
            NetworkApi.init(new NetworkRequiredInfo(application),
                    GlobeConstant.HttpConfig.HOST_URL + ":" + GlobeConstant.HttpConfig.POST);
        }

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    // 程序在内存清理的时候执行（回收内存）
    // HOME键退出应用程序、长按MENU键，打开Recent TASK都会执行
    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}
